using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using AC;

#if UNITY_EDITOR
using UnityEditor;
#endif

[System.Serializable]
public class ActionDialog: Action {

	public bool isCutscene;

	public string dialogueName;
	public DialoguerDialogues diaDia;

	public Signal activatePanel;

	public GameObject hotspot;
	public GameObject mouseDetector;

	public Cutscene toCut;

	public ActionDialog(){

		this.isDisplayed = true;
		title = "Dialogue: Play Dialog";
	}

	public void Awake(){
		activatePanel.target = GameObject.FindGameObjectWithTag (Tags.gameEngine);
		hotspot = GameObject.Find ("_Hotspots");
		mouseDetector = GameObject.Find ("DialoguerMouseDetector");
	}

	#if UNITY_EDITOR

	override public void ShowGUI(){
		isCutscene = EditorGUILayout.Toggle ("Is it a cutscene: ", isCutscene);
		if(isCutscene)
		{
			diaDia = (DialoguerDialogues)EditorGUILayout.EnumPopup("Dialogue name to play: ", diaDia);
			toCut = (Cutscene)EditorGUILayout.ObjectField("Cutscene to Play After: ",toCut, typeof(Cutscene), true);
		}
		else
		{
			diaDia = (DialoguerDialogues)EditorGUILayout.EnumPopup ("Dialogue name to play: ", diaDia);
		}
		AfterRunningOption ();
	}

	#endif

	override public float Run(){

		/*activatePanel.method = "OnDeactivate";
		activatePanel.Invoke ();*/

		//Change all hotspots layer to "Ignore Raycast"
		SetLayerRecursively (hotspot, 2);
		//Activate Huge invisible Box Collider to detect mouse clicks
		mouseDetector.SetActive (true);
		Debug.Log ("diaDia is " + diaDia);
		if (isCutscene == false)
			Dialoguer.StartDialogue (diaDia);
		else
		{
			Dialoguer.StartDialogue(diaDia);
			GameObject.FindWithTag(Tags.gameEngine).GetComponent<DialoguerPrinter>().isCutscene = true;
			GameObject.FindWithTag(Tags.gameEngine).GetComponent<DialoguerPrinter>().nextCutscene = toCut;
		}

		GameObject.FindWithTag (Tags.gameEngine).GetComponent<KickStarter> ().TurnOffAC ();

		return 0.0f;
	}

	private void DialoguerCallback()
	{
		this.isEnabled = true;;
	}

	void SetLayerRecursively(GameObject obj, int newLayer)
	{
		if (null == obj)
		{
			return;
		}
		
		obj.layer = newLayer;
		
		foreach (Transform child in obj.transform)
		{
			if (null == child)
			{
				continue;
			}
			SetLayerRecursively(child.gameObject, newLayer);
		}
	}
}
